﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using AcceptServer;
using AcceptServer.Service;
using Common;
using Model;

namespace PLSServer
{
    public partial class AcceptMainForm : Form
    {
        public AcceptMainForm()
        {
            InitializeComponent();
            label_version.Text = StrVersion;
        }
         
        public static string ServerWebIp;
        //  private static string _serverLanIp;

        private const string StrVersion = "1.0.2_bata3";
        private readonly Hashtable _ipEndPointList = Hashtable.Synchronized(new Hashtable());
        private readonly Hashtable _ipEndPointTimeList = Hashtable.Synchronized(new Hashtable());


        readonly TQueue<byte[]> _dateQueue = new TQueue<byte[]>();
        public static readonly TQueue<DeviceGpsInfo> GpsQueue = new TQueue<DeviceGpsInfo>();
        readonly OperateDataBase _operateDataBase = new OperateDataBase();

        private UdpServer _server;
        private UdpServer _server2;

        private Socket _udpClientChinaNet;
        private Socket _udpClientUniCom;
        private IPEndPoint _ipepChinaNet;
        private IPEndPoint _ipepUniCom;


        private int _dataHandlerThreadCount = 1;
        private int _dataBaseHandlerThreadCount = 1;


        private Thread[] _threadDataHandler;//数据处理线程
        private Thread[] _threadTaxiGpsHistoryInfoHandler;//数据处理线程
         
        // readonly IPEndPoint _ipep = new IPEndPoint(IPAddress.Any, ConstParameters.AstPort);
        private const string LocalhostIP = "127.0.0.1";


        private ThreadServiceHost _threadServiceHost;
        
        private Thread _ipEndPointClearThread;
        private Thread _threadClearDevice;
        private Thread _threadUpdateDeviceInfo;
        private Thread _threadAddGpsToQueue;
        private Thread _threadSaveGpsInfoToDb;

        public static string PhoneUserClientVersion="100";
        public static string SpecialCarClientVersion = "100";


        public static Hashtable DeviceList = Hashtable.Synchronized(new Hashtable());
        private IoServer _iocpServer ;
        private int _timeSleepAddGpsInfoToQueue;
        private int _timeSleepUpdateDevice;
        private int _timeSleepClearDevice;
        private int _timeOfDeviceDrop;
        public static int MaxGpsInfoCountInOneData;
        private int _timeSleepSaveGpsInfoToDb;
         
        //!--1
        private void StartServecie()
        {
            if (!CheckDataBasesConnection())
            {
                return;
            }

            //----save config
            string[] config = new string[6];
            config[0] = textBox_PosIP.Text;
            config[1] = textBox_ChinaNetIp.Text;
            config[2] = textBox_UnicomIp.Text;
            config[3] = textBox_PhoneNumber.Text;
            config[4] = textBox_MaxTcpConnection.Text;
            config[5] = textBox_TcpBufferSize.Text;
            OperateConfig.SaveAcceptServerConfig(config);          

            //----timing config
            string[] timingConfig = new string[6];
            timingConfig[0] = textBox_saveGpsTime.Text;
            timingConfig[1] = textBox_updateDeviceInfo.Text;
            timingConfig[2] = textBox_clearDeviceTime.Text;
            timingConfig[3] = textBox_deviceDropTime.Text;
            timingConfig[4] = textBox_maxGpsInfoCount.Text;
            timingConfig[5] = textBox_SaveGpsToDbTime.Text;

            if (!CheckTimingConfig(timingConfig))
            {
                return;
            }
            OperateConfig.SaveTimingConfig(timingConfig);

            StartWcfService();
            try
            {
                //============初始化IOCP==============
                int maxConnectCount =10000;
                int maxBufferSize = 1;
                if (!int.TryParse(config[4], out maxConnectCount))
                {
                    MessageBox.Show("请输入正确的TCP最大连接数量值！");
                    return;
                }
                if (!int.TryParse(config[5], out maxBufferSize))
                {
                    MessageBox.Show("请输入正确的单个TCP缓存大小！");
                    return;
                }
                _iocpServer = new IoServer(maxConnectCount,maxBufferSize*1024);
                _iocpServer.Start(IPAddress.Parse(textBox_ChinaNetIp.Text),
                    ConstParameters.TcpListene);
                _iocpServer.mainForm = this;
               

                if (textBox_ChinaNetIp.Text != LocalhostIP)
                {
                    _server = new UdpServer(textBox_ChinaNetIp.Text, ConstParameters.AstPort);
                    _server.OnReceivedData += server_OnDataReceived;
                    _server.Start();
                }

                if (textBox_UnicomIp.Text != LocalhostIP)
                {
                    _server2 = new UdpServer(textBox_UnicomIp.Text, ConstParameters.AstPort);
                    _server2.OnReceivedData += server_OnDataReceived;
                    _server2.Start();
                }

                if (textBox_ChinaNetIp.Text != LocalhostIP)
                {
                    _ipepChinaNet = new IPEndPoint(IPAddress.Parse(textBox_ChinaNetIp.Text), ConstParameters.AstPort);
                    _udpClientChinaNet = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _udpClientChinaNet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpClientChinaNet.Bind(_ipepChinaNet);
                }
                if (textBox_UnicomIp.Text != LocalhostIP)
                {
                    _ipepUniCom = new IPEndPoint(IPAddress.Parse(textBox_UnicomIp.Text), ConstParameters.AstPort);
                    _udpClientUniCom = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    _udpClientUniCom.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                    _udpClientUniCom.Bind(_ipepUniCom);
                }
               // _threadTaxiGpsHistoryInfoHandler = new Thread[_dataBaseHandlerThreadCount];
       

                this._threadDataHandler = new Thread[_dataHandlerThreadCount];
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    this._threadDataHandler[i] = new Thread(UdpSendData);
                    this._threadDataHandler[i].Start();
                }

                _ipEndPointClearThread = new Thread(IpEndPointClear) { IsBackground = true, Name = "IPEndPointClearThread----------------------------------------------" }; ;
                _ipEndPointClearThread.Start();

                _threadClearDevice = new Thread(ClearDeviceInCache) { IsBackground = true, Name = "TaxiClearThread ----------------------------------------" }; ;
                _threadClearDevice.Start();

                _threadUpdateDeviceInfo = new Thread(UpdateDeviceInfoToDataBase) { IsBackground = true };
                _threadUpdateDeviceInfo.Start();

                _threadAddGpsToQueue = new Thread(AddDeviceGpsInfoToQueue){IsBackground = true};
                _threadAddGpsToQueue.Start();

                _threadSaveGpsInfoToDb = new Thread(SaveGpsQueueToDataBase) { IsBackground = true };
                _threadSaveGpsInfoToDb.Start();
            }
            catch (Exception ex)
            {
                InitControlAfterStopService();
                CommonRoutine.HandlingExceptions(ex, true);
                LogService.WriteLog("AcceptMainForm.cs-155");
            }
 
        }
         
        void server_OnDataReceived(object sender, EventArgs e)
        {
            SocketAsyncEventArgs socketAsyncEventArgs = e as SocketAsyncEventArgs;
            if (socketAsyncEventArgs != null)
            {
                if (socketAsyncEventArgs.BytesTransferred >= ConstParameters.MhLenth)
                {
                    byte[] receData = new byte[socketAsyncEventArgs.BytesTransferred];
                    Array.Copy(socketAsyncEventArgs.Buffer, 0, receData, 0, receData.Length);
                    byte[] realData = OperateAgreement.RestoreReceData(receData);



                    if (OperateAgreement.JudgeisCompleteData(realData))
                    {
                        string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                        _ipEndPointTimeList[phoneNumber] = DateTime.Now;
                        _ipEndPointList[phoneNumber] = socketAsyncEventArgs.RemoteEndPoint;
                        _dateQueue.Enqueue(receData);
                    }

                }

            }


        }

        private void UdpSendData()
        {

            while (true)
            {
                if (_dateQueue.Count < 1)
                {
                    Thread.Sleep(1000);
                    continue;
                }

                byte[] receData;
                lock (_dateQueue)
                {
                    receData = _dateQueue.Dequeue();
                }



                byte[] realData = OperateAgreement.RestoreReceData(receData);
                ushort messageId = OperateAgreement.GetMessageIdInMessageHead(realData);
                string phoneNumber = OperateAgreement.GetPhoneNumInMessageHead(realData);

                Socket sendSocket = JudgeIsUnicomNumber(phoneNumber);



                IPEndPoint ipEndPoint = _ipEndPointList[phoneNumber] as IPEndPoint;
                if (ipEndPoint == null) continue;
                byte[] sendData = new byte[1];
                try
                {
                    OperateCmdData operateCmdData = new OperateCmdData(); ;
                    sendData = operateCmdData.AnalysisMessageId(realData, ipEndPoint.Address);
                }
                catch (Exception ex)
                {
                    CommonRoutine.HandlingExceptions(ex);
                    LogService.WriteLog("AcceptMainForm.cs-405");
                    continue;
                }
                #region Send Bytes

                if (sendData != null && sendData.Length >= ConstParameters.MhLenth)
                {
                    try
                    {
                        //  sendSocket.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        //_server.SendData(sendData, ipEndPoint);
                        _udpClientChinaNet.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        _udpClientUniCom.SendTo(sendData, sendData.Length, SocketFlags.None, ipEndPoint);
                        
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-428");
                        continue;
                    }
                }
                #endregion

            }


            #region LogPrint
            LogService.WriteLog(Thread.CurrentThread.Name + "----Snen Thread 退出----");
            #endregion
        }

        public Socket JudgeIsUnicomNumber(string phoneNumber)
        {
            #region 单线服务器 处理
            //不会出现这种情况。两个都为空的话没程序就没有收发消息的流程。
            // if (_udpClientUniCom == null && _udpClientChinaNet == null) 
            if (_udpClientUniCom == null && _udpClientChinaNet != null)
            {
                _udpClientUniCom = _udpClientChinaNet;
                return _udpClientChinaNet;
            }
            if (_udpClientUniCom != null && _udpClientChinaNet == null)
            {
                _udpClientChinaNet = _udpClientUniCom;
                return _udpClientUniCom;
            }
            #endregion
            //130、131、132、145、155、156、185、186 
            if (phoneNumber.StartsWith("130") || phoneNumber.StartsWith("131") || phoneNumber.StartsWith("132") ||
                phoneNumber.StartsWith("145") || phoneNumber.StartsWith("155") || phoneNumber.StartsWith("156") ||
                phoneNumber.StartsWith("185") || phoneNumber.StartsWith("186"))
            {
                return _udpClientUniCom;
            }
            else
            {
                return _udpClientChinaNet;
            }
        }


        private void IpEndPointClear()
        {
            while (true)
            {
                Thread.Sleep(300 * 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                lock (_ipEndPointTimeList.SyncRoot)
                {
                    foreach (DictionaryEntry dictionaryEntry in _ipEndPointTimeList)
                    {
                        DateTime updatatime = (DateTime)dictionaryEntry.Value;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                        if (timeSpan.TotalSeconds > 300)
                        {
                            delKey.Add(dictionaryEntry.Key);
                            LogService.WriteDebugLog(dictionaryEntry.Key + "---" + now.ToString() + "---" + updatatime.ToString() + "退出登录！", DateTime.Now, dictionaryEntry.Key.ToString());
                        }
                    }
                }

                foreach (string phoneNumber in delKey)
                {
                    try
                    {
                        _ipEndPointTimeList.Remove(phoneNumber);
                        _ipEndPointList.Remove(phoneNumber);


                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-515");
                    }

                }
                Invoke(new MethodInvoker(delegate()
                {
                    label_SokcetCount.Text = _ipEndPointList.Count.ToString(CultureInfo.InvariantCulture) + "," + DateTime.Now.ToString();
                }));


            }

        }



        private void InitControlAfterStopService()
        {
            spState.Text = @" 监听服务未启动 ...";
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            textBox_PosIP.Enabled = true;
            textBox_ChinaNetIp.Enabled = true;
            textBox_UnicomIp.Enabled = true;
            textBox_PhoneNumber.Enabled = true;
            textBox_DataBaseHandlerThreadCount.Enabled = true;
            textBox_DataHandlerThreadCount.Enabled = true;
            textBox_MaxTcpConnection.Enabled = true;
            textBox_TcpBufferSize.Enabled = true;

            textBox_datBaseName.Enabled = true;
            textBox_passWord.Enabled = true;
            textBox_serverName.Enabled = true;
            textBox_userName.Enabled = true;

            if (_threadDataHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataHandlerThreadCount; i++)
                {
                    if (this._threadDataHandler[i].IsAlive) this._threadDataHandler[i].Abort();
                }
            }

            if (_threadTaxiGpsHistoryInfoHandler != null)
            {
                //终止所有的数据处理线程
                for (int i = 0; i < _dataBaseHandlerThreadCount; i++)
                {
                    if (this._threadTaxiGpsHistoryInfoHandler[i].IsAlive) this._threadTaxiGpsHistoryInfoHandler[i].Abort();
                }
            }
             

            //if (_addTaxiGpsHistoryInfoQueue != null) _addTaxiGpsHistoryInfoQueue.Abort();
            if (_ipEndPointClearThread != null) _ipEndPointClearThread.Abort();
      
            // if (_server != null) { _server.Stop(); }
        }



        private void InitControlAfterStartService()
        {
            spState.Text = @" 监听服务已启动 ...";
            button_startListening.Enabled = false;
            button_stopListening.Enabled = true;
            textBox_PosIP.Enabled = false;
            textBox_ChinaNetIp.Enabled = false;
            textBox_UnicomIp.Enabled = false;
            textBox_PhoneNumber.Enabled = false;
            textBox_DataBaseHandlerThreadCount.Enabled = false;
            textBox_DataHandlerThreadCount.Enabled = false;

            textBox_datBaseName.Enabled = false;
            textBox_passWord.Enabled = false;
            textBox_serverName.Enabled = false;
            textBox_userName.Enabled = false;

            textBox_MaxTcpConnection.Enabled = false;
            textBox_TcpBufferSize.Enabled = false;
        }

 





        private void button_startListening_Click(object sender, EventArgs e)
        {
            if (!CommonRoutine.IsValidIp(textBox_PosIP.Text))
            {
                MessageBox.Show(@"请检查位置服务器IP格式");
                textBox_PosIP.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_ChinaNetIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP1格式");
                textBox_ChinaNetIp.Focus();
                return;
            }
            if (!CommonRoutine.IsValidIp(textBox_UnicomIp.Text))
            {
                MessageBox.Show(@"请检查接入服务器IP2格式");
                textBox_UnicomIp.Focus();
                return;
            }


            if (!int.TryParse(textBox_DataBaseHandlerThreadCount.Text, out _dataBaseHandlerThreadCount))
            {
                MessageBox.Show(@"数据库处理线程数：  请输入数字");
                textBox_DataBaseHandlerThreadCount.Focus();
                return;
            }
            if (!int.TryParse(textBox_DataHandlerThreadCount.Text, out _dataHandlerThreadCount))
            {
                MessageBox.Show(@"网络数据处理线程数 ：请输入数字");
                textBox_DataHandlerThreadCount.Focus();
                return;
            }
            StartServecie();

        }

        private void button_stopListening_Click(object sender, EventArgs e)
        {

            try
            {
                _iocpServer.Stop();
                _ipEndPointList.Clear();
                _ipEndPointTimeList.Clear();
                label_SokcetCount.Text = "0";
                InitControlAfterStopService();                 
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-891");
            }

        }

        private void HideServer_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Minimized;
            ShowInTaskbar = false;
            Visible = false;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
 
            
            button_startListening.Enabled = true;
            button_stopListening.Enabled = false;
            string[] config = OperateConfig.GetAcceptServerConfig();
            if (config != null && config.Length == 10)
            {
                textBox_PosIP.Text = config[0];
                textBox_ChinaNetIp.Text = config[1];
                textBox_UnicomIp.Text = config[2];
                textBox_PhoneNumber.Text = config[3];            
                textBox_datBaseName.Text = config[4];
                textBox_serverName.Text = config[5];
                textBox_userName.Text = config[6];
                textBox_passWord.Text = config[7];
                textBox_MaxTcpConnection.Text = config[8];
                textBox_TcpBufferSize.Text = config[9];
            }
            string[] timingConfig = OperateConfig.GetTimingConfig();
            textBox_saveGpsTime.Text = timingConfig[0];
            textBox_updateDeviceInfo.Text = timingConfig[1];
            textBox_clearDeviceTime.Text = timingConfig[2];
            textBox_deviceDropTime.Text = timingConfig[3];
            textBox_maxGpsInfoCount.Text = timingConfig[4];
            textBox_SaveGpsToDbTime.Text = timingConfig[5];

        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                _ipEndPointList.Clear();
                label_SokcetCount.Text = "0";

                InitControlAfterStopService();

            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex);
                LogService.WriteLog("AcceptMainForm.cs-943");
            }
            notifyIcon1.Visible = false;
            Environment.Exit(0);
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
                ShowInTaskbar = true;
                Visible = true;
                Focus();
            }
            else
            {
                WindowState = FormWindowState.Minimized;
                ShowInTaskbar = false;
                Visible = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label_SokcetCount.Text = _iocpServer.numConnectedSockets.ToString();
            //string showtext = _ipEndPointList.Count.ToString();           
            //lock (_ipEndPointList.SyncRoot)
            //{
            //    foreach (DictionaryEntry dictionaryEntry in _ipEndPointList)
            //    {
            //        showtext = showtext + dictionaryEntry.Key + Environment.NewLine;
            //    }
            //}            
            //MessageBox.Show(showtext);
        }

        private void button_TestConnection_Click(object sender, EventArgs e)
        {
            string[] config = new[]
            {
                 textBox_datBaseName.Text,
                 textBox_serverName.Text,
                 textBox_userName.Text,
                textBox_passWord.Text
            };
            OperateConfig.SaveAcceptServerDataBaseConfig(config);
            if (CheckDataBasesConnection())
            {
                BLL.SysManage.UpdataConnectstring();
                MessageBox.Show(@"数据库连接成功！");

            }
        }

        /// <summary>
        ///!--4 return 1 means succeed ,return 0 means false
        /// </summary>
        public bool CheckDataBasesConnection()
        {
            if (BLL.SysManage.CheckDb(textBox_datBaseName.Text) == 0)
            {
                MessageBox.Show(@"系统数据库连接失败！请检查配置。");
                return false;
            }
            return true;
        }



        private void button1_Click(object sender, EventArgs e)
        {

            label_SokcetCount.Text = _ipEndPointList.Count.ToString();
            label_DataHandlerThreadCount.Text = _dateQueue.Count.ToString();
            label_DataBaseHandlerThreadCount.Text = GpsQueue.Count.ToString();
            
        }

        private void ClearDeviceInCache()
        {
            while (true)
            {            
                Thread.Sleep(_timeSleepClearDevice *60* 1000);
                DateTime now = DateTime.Now;
                ArrayList delKey = new ArrayList();
                lock (DeviceList.SyncRoot)
                {

                    foreach (DeviceInfo device in DeviceList.Values)
                    {
                        DateTime updatatime = device.UpdateTime;
                        TimeSpan timeSpan = new TimeSpan(now.Ticks - updatatime.Ticks);
                        if (timeSpan.TotalSeconds > _timeOfDeviceDrop*60)
                        {
                            delKey.Add(device.PhoneNumber);
                            //LogService.WriteDebugLog(taxiInfo.DriverPhoneNumber + "---"
                            //    + now.ToString() + "---" + updatatime.ToString() + "退出登录！", DateTime.Now);
                        }
                    }                  
                }

                foreach (string phoneNumber in delKey)
                {
                    try
                    {
                        DeviceList.Remove(phoneNumber);                     
                    }
                    catch (Exception ex)
                    {
                        CommonRoutine.HandlingExceptions(ex);
                        LogService.WriteLog("AcceptMainForm.cs-515");
                    }

                }
                //Invoke(new MethodInvoker(delegate()
                //{
                //    label_SokcetCount.Text = _ipEndPointList.Count.ToString(CultureInfo.InvariantCulture) + "," + DateTime.Now.ToString();
                //}));
            }
        }

        private void UpdateDeviceInfoToDataBase()
        {
            while (true)
            {
                Thread.Sleep(_timeSleepUpdateDevice*60*1000);
                 
                List<DeviceInfo> deviceInfos = new List<DeviceInfo>();                
                lock (DeviceList.SyncRoot)
                {
                  deviceInfos.AddRange(DeviceList.Values.Cast<DeviceInfo>());
                }
                foreach (DeviceInfo device in deviceInfos)
                {
                    if (_operateDataBase.DeviceExists(device.Emi))
                    {
                        _operateDataBase.DeviceUpdate(device);
                    }
                    else
                    {
                        _operateDataBase.DeviceAdd(device);
                    }
                }              
            }
        }

        private void AddDeviceGpsInfoToQueue()
        {
            while (true)
            {
                Thread.Sleep(_timeSleepAddGpsInfoToQueue  * 1000);                
                List<DeviceInfo> deviceInfos = new List<DeviceInfo>();                 
                lock (DeviceList.SyncRoot)
                {
                    deviceInfos.AddRange(DeviceList.Values.Cast<DeviceInfo>());
                }
                foreach (DeviceInfo deviceInfo in deviceInfos)
                {
                    if (deviceInfo.Lat <10|| deviceInfo.Lat<10)
                    {
                        continue;
                    }
                     
                    DeviceGpsInfo gpsInfo = new DeviceGpsInfo();
                    gpsInfo.Emi = deviceInfo.Emi;
                    gpsInfo.PhoneNumber = deviceInfo.PhoneNumber;
                    gpsInfo.Lat = deviceInfo.Lat;
                    gpsInfo.Lng = deviceInfo.Lng;
                    gpsInfo.Speed = deviceInfo.Speed;
                    gpsInfo.State = deviceInfo.State;
                    gpsInfo.Angle = deviceInfo.Angle;
                    gpsInfo.UpdateTime = deviceInfo.UpdateTime;
                    GpsQueue.Enqueue(gpsInfo);
                }                
            }
        }

        private void SaveGpsQueueToDataBase()
        {
            while (true)
            {
                Thread.Sleep(_timeSleepSaveGpsInfoToDb*60*1000);                 
                if (GpsQueue.Count < 1)
                {
                    Thread.Sleep(_timeSleepSaveGpsInfoToDb * 60 * 1000);
                    continue;
                }
                try
                {
                    List<DeviceGpsInfo> list = new List<DeviceGpsInfo>();
                    while (GpsQueue.Count > 0)
                    {
                        list.Add(GpsQueue.Dequeue());
                        if (list.Count == 5000 || GpsQueue.Count == 0)
                        {
                            //保存到数据库
                            int succeed = _operateDataBase.AddGpsInfoInArray(list.ToArray());
                        }
                    }                                      
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }


        private  void StartWcfService()
        {            
            try
            {
                _threadServiceHost = new ThreadServiceHost();
                _threadServiceHost.Start();
                InitControlAfterStartService();      
            }
            catch (Exception ex)
            {
                CommonRoutine.HandlingExceptions(ex, true);
                //OperateConfig.SavePosServerConfig("0", comstr);
                System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
                Environment.Exit(0);
            }
        }

        private void button_saveTimingConfig_Click(object sender, EventArgs e)
        {
            string[] timingConfig = new string[6];
            timingConfig[0] = textBox_saveGpsTime.Text;
            timingConfig[1] = textBox_updateDeviceInfo.Text;
            timingConfig[2] = textBox_clearDeviceTime.Text;
            timingConfig[3] = textBox_deviceDropTime.Text;
            timingConfig[4] = textBox_maxGpsInfoCount.Text;
            timingConfig[5] = textBox_SaveGpsToDbTime.Text;

            if (!CheckTimingConfig(timingConfig))
            {
                return;
            }
            OperateConfig.SaveTimingConfig(timingConfig);
            textBox_saveGpsTime.Enabled = false;
            textBox_updateDeviceInfo.Enabled = false;
            textBox_clearDeviceTime.Enabled = false;
            textBox_deviceDropTime.Enabled = false;
            textBox_maxGpsInfoCount.Enabled = false;
            textBox_SaveGpsToDbTime.Enabled = false;
            button_saveTimingConfig.Enabled = false;
            button_modifyTimingConfig.Enabled = true;

            MessageBox.Show("配置保存成功！");
        }

        private void button_modifyTimingConfig_Click(object sender, EventArgs e)
        {
            textBox_saveGpsTime.Enabled = true;
            textBox_updateDeviceInfo.Enabled = true;
            textBox_clearDeviceTime.Enabled = true;
            textBox_deviceDropTime.Enabled = true;
            textBox_maxGpsInfoCount.Enabled = true;
            textBox_SaveGpsToDbTime.Enabled = true;
            button_saveTimingConfig.Enabled = true;            
            button_modifyTimingConfig.Enabled = false;
            textBox_saveGpsTime.Focus();
        }

        private bool CheckTimingConfig(string[] timingConfig)
        {
            if (!int.TryParse(timingConfig[0], out _timeSleepAddGpsInfoToQueue))
            {
                MessageBox.Show("定时记录GPS数据到队列配置错误，必须为整数!");
                return false;
            }
            if (_timeSleepAddGpsInfoToQueue < 10)
            {
                MessageBox.Show("定时保存GPS数据到队列配置错误，不能低于10!");
                return false;
            }

            if (!int.TryParse(timingConfig[5], out _timeSleepSaveGpsInfoToDb))
            {
                MessageBox.Show("定时保存GPS到数据库配置错误，必须为整数!");
                return false;
            }
            if (_timeSleepSaveGpsInfoToDb < 10)
            {
                MessageBox.Show("定时保存GPS到数据库配置错误，不能低于10!");
                return false;
            }

            if (!int.TryParse(timingConfig[1], out _timeSleepUpdateDevice))
            {
                MessageBox.Show("定时更新设备信息到数据库的配置值错误，必须为整数！");
                return false;
            }
            if (_timeSleepUpdateDevice < 10)
            {
                MessageBox.Show("定时更新设备信息到数据库的配置值过小，不能低于10！");
                return false;
            }
            if (!int.TryParse(timingConfig[2], out _timeSleepClearDevice))
            {
                MessageBox.Show("定时清楚未更新信息设备的配置时间错误，必须为整数！");
                return false;
            }
            if (_timeSleepClearDevice < 1)
            {
                MessageBox.Show("定时清楚未更新信息设备的配置时间过小，不能低于1！");
                return false;
            }
            if (!int.TryParse(timingConfig[3], out _timeOfDeviceDrop))
            {
                MessageBox.Show("设备无更新消息记为掉线的配置时间错误，必须为整数！");
                return false;
            }
            if (_timeOfDeviceDrop < 1)
            {
                MessageBox.Show("设备无更新消息记为掉线的配置时间过小，不能低于1！");
                return false;
            }
            if (!int.TryParse(timingConfig[4], out MaxGpsInfoCountInOneData))
            {
                MessageBox.Show("每个数据包中最大GPS信息数量配置错误，必须为整数！");
                return false;
            }
            if (MaxGpsInfoCountInOneData < 10 || MaxGpsInfoCountInOneData > 75)
            {
                MessageBox.Show("每个数据包中最大GPS信息数量配置超出正常（10~75）！");
                return false;
            }
            return true;
        }
    }

}
